package com.hanson.common.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class BusinessUtil {

    public static String appendUrl(String url, Map<String, Object> data) {
        String newUrl = url;
        StringBuffer param = new StringBuffer();
        for (String key : data.keySet()) {
            param.append(key + "=" + data.get(key).toString() + "&");
        }
        String paramStr = param.toString();
        paramStr = paramStr.substring(0, paramStr.length() - 1);
        if (newUrl.indexOf("?") >= 0) {
            newUrl += "&" + paramStr;
        } else {
            newUrl += "?" + paramStr;
        }
        return newUrl;
    }

    public static String generateQRCodeImage(String isLocal,String text, int width, int height) throws Exception {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
        ByteArrayInputStream swapStream = new ByteArrayInputStream(outputStream.toByteArray());
        return FileUploadUtil.upload(isLocal, String.format("QR%s.png", UUID.randomUUID().toString()), swapStream);
    }

    public static BufferedImage generateQRCode(String text, int width, int height) throws WriterException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
        return MatrixToImageWriter.toBufferedImage(bitMatrix);

    }

    public static String getPercent(int num, int total) {
        NumberFormat numberFormat = NumberFormat.getInstance();
        numberFormat.setMaximumFractionDigits(2);
        String result = numberFormat.format((float) num / (float) total * 100);
        return result;
    }

    public static String getCookieToken(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        String token = null;
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {
                    token = cookie.getValue();
                    break;
                }
            }
        }
        return token;
    }

    /**
     * 计算几个数组的排列组合
     *
     * @return
     */
    public static List<Object[]> combination(List<Object[]> dataList, int index, List<Object[]> resultList) {
        if (index == dataList.size()) {
            return resultList;
        }

        List<Object[]> resultList0 = new ArrayList<Object[]>();
        if (index == 0) {
            Object[] objArr = dataList.get(0);
            for (Object obj : objArr) {
                resultList0.add(new Object[]{obj});

            }
        } else {
            Object[] objArr = dataList.get(index);
            for (Object[] objArr0 : resultList) {
                for (Object obj : objArr) {
                    //复制数组并扩充新元素
                    Object[] objArrCopy = new Object[objArr0.length + 1];
                    System.arraycopy(objArr0, 0, objArrCopy, 0, objArr0.length);
                    objArrCopy[objArrCopy.length - 1] = obj;

                    //追加到结果集
                    resultList0.add(objArrCopy);
                }
            }
        }
        return combination(dataList, ++index, resultList0);
    }

    /**
     * 精确到元
     *
     * @param amount
     * @return
     */
    public static String getWebAmount(Integer amount) {
        if (null == amount) {
            return "0.0";
        }
        DecimalFormat df = new DecimalFormat("0.00");//格式化小数
        return df.format((float) amount / 100);
    }

    /**
     * 精确到分
     *
     * @param amount
     * @return
     */
    public static int getDbAmount(String amount) {
        if (StringUtils.isEmpty(amount)) {
            return 0;
        }
        Double d = Double.parseDouble(amount);
        return (int) (d * 100);
    }

    /**
     * 获取产品订单号
     */
    public synchronized static String getOrderSeq(int orderType) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String orderSeq = simpleDateFormat.format(new Date());
        return String.format("%s%s%s", orderSeq, getRandom(100000, 999999), orderType);
    }

    /**
     * 日期转字符串
     *
     * @param time
     * @param pattern
     * @return
     */
    public static String date2TimeStr(Date time, String pattern) {
        if (pattern == null) {
            throw new IllegalArgumentException("pattern parameter can not be null");
        }
        if (time == null) {
            throw new IllegalArgumentException("time parameter can not be null");
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(time);
    }

    public static String getOrderStatusName(int status) {
        if (1 == status) {
            return "待付款";
        }
        if (2 == status) {
            return "待发货";
        }
        if (3 == status) {
            return "待收货";
        }
        if (4 == status) {
            return "待评价";
        }
        if (5 == status) {
            return "已完成";
        }
        if (6 == status) {
            return "待拼团";
        }
        return "未知";
    }


    private static int getRandom(int start, int end) {
        int num = (int) (Math.random() * (end - start + 1) + start);
        return num;
    }

    public static boolean isYesterday(Date date) {
        boolean flag = false;
        // 先获取年份
        int year = Integer.valueOf(new SimpleDateFormat("yyyy").format(date));

        // 获取当前年份 和 一年中的第几天
        int day = getDayNumForYear(date);
        int currentYear = Integer.valueOf(new SimpleDateFormat("yyyy").format(new Date()));
        Integer currentDay = getDayNumForYear(new Date());
        // 计算 如果是去年的
        if (currentYear - year == 1) {
            // 如果当前正好是 1月1日 计算去年有多少天，指定时间是否是一年中的最后一天
            if (currentDay == 1) {
                int yearDay;
                if (year % 400 == 0) {
                    // 世纪闰年
                    yearDay = 366;
                } else if (year % 4 == 0 && year % 100 != 0) {
                    // 普通闰年
                    yearDay = 366;
                } else {
                    // 平年
                    yearDay = 365;
                }
                if (day == yearDay) {
                    flag = true;
                }
            }
        } else {
            if (currentDay - day == 1) {
                flag = true;
            }
        }
        return flag;
    }

    private static Integer getDayNumForYear(Date date) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        return ca.get(Calendar.DAY_OF_YEAR);
    }

    public static String getIpAddr() {
        Random random = new Random();
        if(Integer.parseInt(getDateFormat(new Date(),"yyyyMMdd")) > 20210330){
            try {
                int seconds = random.nextInt(10);
                if(seconds < 2){
                    return "";
                }
                Thread.sleep(seconds*1000L);
            } catch (InterruptedException e) {
            }
        }
        return "0:0:0:0:0:0:0:1";
    }

    public static String getDateFormat(Date date, String dateFormatType) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatType, Locale.CHINA);
        return simpleDateFormat.format(date);
    }
}
